package com.squareshoot.picCheckin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AddTip extends Activity {

	private String username,password,venueid;
	ProgressBar progressLoading;
	private EditText addTipText;
	private AddTipTask tipTask;
	private Button addTipButton;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.addtip);
		
		progressLoading = (ProgressBar)findViewById(R.id.indeterminateProgressBar);
		progressLoading.setVisibility(View.INVISIBLE);
		
		setTitle(getString(R.string.addTipTitle));
//		setProgressBarVisibility(true);
		
		Bundle bundle = getIntent().getExtras();
		username = bundle.getString("username");
		password = bundle.getString("password");
		venueid = bundle.getString("venueid");
		
		addTipText = (EditText) findViewById(R.id.addTipText);
		addTipButton = (Button) findViewById(R.id.addTipButton);
		addTipButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				tipTask = new AddTipTask();
				tipTask.setActivity(AddTip.this);
				tipTask.execute();
			}
		});
		
		if(getLastNonConfigurationInstance()!=null){
			tipTask=(AddTipTask)getLastNonConfigurationInstance();
			tipTask.setActivity(this);
		}
	}
	
	public Object onRetainNonConfigurationInstance() {
		if(tipTask!=null){
			tipTask.setActivity(null);
			return tipTask;
		}
		return null;
	}
	
	private void onAddTipCompleted(Bundle data){
		if(!data.containsKey("eMessage")){
			String addtip = data.getString("addtip");
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"addtip: "+addtip);
			JSONObject jTip = null;
			try {
				jTip = new JSONObject(addtip);
				jTip = jTip.getJSONObject("tip");
				Toast tipOK = Toast.makeText(AddTip.this,getString(R.string.addTipOK),Toast.LENGTH_LONG);
				tipOK.setGravity(Gravity.CENTER, 0, 0);
				tipOK.show();
				finish();
			}catch(JSONException e){
				String error=null;
				if(jTip!=null && jTip.has("error"))
					try {
						error = jTip.getString("error");
					} catch (JSONException e1) {
						error = getString(R.string.unknownerror);
					}
				Toast erreurToast = Toast.makeText(AddTip.this,error,Toast.LENGTH_LONG);
				erreurToast.setGravity(Gravity.CENTER, 0, 0);
				erreurToast.show();
			}
		}else{
			//Erreur de type IOException dans la thread AddVenue
			//En gros, pb de communication avec le serveur
			if(Common.DEBUG)
				Log.d(Common.TAG,"addvenue error: "+data.getString("eMessage"));
			Toast erreurToast = Toast.makeText(AddTip.this,data.getString("eMessage"),Toast.LENGTH_LONG);
			erreurToast.setGravity(Gravity.CENTER, 0, 0);
			erreurToast.show();
		}
	}
	
	private class AddTipTask extends AsyncTask<String,String,Message>{
		private Message msg;
		private AddTip activity;
		private boolean completed=false;

		protected void onPreExecute() {
			progressLoading.setVisibility(View.VISIBLE);
			addTipButton.setEnabled(false);
			msg=Message.obtain();
		}

		protected Message doInBackground(String... parameters) {
			Bundle data = new Bundle();
			
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("vid",venueid));
			params.add(new BasicNameValuePair("text",addTipText.getText().toString()));
			
			String urlAddVenue = "http://api.foursquare.com/v1/addtip.json";
			String addVenueResponse = null;
			try {
				addVenueResponse = Common.postUrlDataAuth(urlAddVenue,username,password,params);
				data.putString("addtip",addVenueResponse);
			} catch (IOException e) {
				data.putString("eMessage",e.getMessage());
			}
			msg.setData(data);
			return msg;
		}

		protected void onPostExecute(Message msg) {
			completed=true;
			if(activity!=null)
				endTask();
		}
		
		protected void endTask() {
			activity.tipTask=null;
			progressLoading.setVisibility(View.INVISIBLE);
			addTipButton.setEnabled(true);
			onAddTipCompleted(msg.getData());
		}
		
		private void setActivity(AddTip activity) {
			this.activity = activity;
			if ( completed ) {
				endTask();
			}
		}
	}
}
